#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : lei.wang
import jwt
from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication
from utils.helper.token_helper import TokenHelper
from apps.user.models import User


class TokenAuthentication(BaseAuthentication):

    def authenticate(self, request):
        if 'Authorization' not in request.headers:
            raise exceptions.AuthenticationFailed('Authorization 请求头缺失')
        token_str = request.headers['Authorization']
        if 'Bearer' not in token_str:
            raise exceptions.AuthenticationFailed('Bearer token is missing')

        token = token_str.split(' ')[1]
        try:
            user_payload = TokenHelper.verify_token(token)
            setattr(request, 'current_user', User.objects.get(id=user_payload['user_id']))
        except jwt.ExpiredSignatureError:
            raise exceptions.AuthenticationFailed('Token is expired')
        except jwt.InvalidTokenError:
            raise exceptions.AuthenticationFailed('Invalid token')
        return None
